package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.AliOSSComment;
import com.lebang.component.RedisClient;
import com.lebang.domain.ClickStrategyDetail;
import com.lebang.domain.MemberClickRouse;
import com.lebang.domain.TaskRouse;
import com.lebang.domain.TaskRouseDetail;
import com.lebang.example.TaskRouseDetailExample;
import com.lebang.mapper.ClickStrategyDetailMapper;
import com.lebang.mapper.MemberClidkRouseRecordMapper;
import com.lebang.mapper.TaskRouseDetailMapper;
import com.lebang.mapper.TaskRouseMapper;
import com.lebang.model.Whether;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 数据源下载任务详情
 *
 * @Author hwq
 * @Date 2020-01-05
 */
@Service
@Slf4j
public class TaskRouseDetailService extends BaseService<TaskRouseDetail, Long, TaskRouseDetailExample> {
    public static final String ROUSE_QUEUE = "task_rouse_queue";
    @Autowired
    private AliOSSComment aliOSSComment;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private TaskRouseMapper rouseMapper;
    @Autowired
    private TaskRouseDetailMapper taskRouseDetailMapper;
    @Autowired
    private ClickStrategyDetailMapper clickStrategyDetailMapper;
    private static final String KEY = "earTaskRouseDetail:";
    @Autowired
    private MemberClidkRouseRecordMapper clidkRouseRecordMapper;

    public boolean add(String pkgName, String appName, String downUrl, String icon, Long id) {

        TaskRouseDetailExample example=new TaskRouseDetailExample();
        example.createCriteria().andAppNameEqualTo(appName);
        if(this.countByExample(example)>0){
            return true;
        }
        if(id==6){
            return true;
        }
        TaskRouseDetail detail = new TaskRouseDetail();
        detail.setCreateTime(LocalDateTime.now());
        detail.setHasDeleted(Whether.NO.getDbIndex());
        detail.setPkgName(pkgName);
        detail.setAppName(appName);
        detail.setDownUrl("");
        detail.setIcon(icon);
        detail.setRouseId(id);
        detail.setEnable(Whether.NO.getDbIndex());
        detail.setOldUrl(downUrl);
        this.insertModel(detail);
        redisClient.lpush(ROUSE_QUEUE, JSON.toJSONString(detail));
        return true;
    }

    public void onMessage(String str) {
        try {
            TaskRouseDetail detail = JSON.parseObject(str, TaskRouseDetail.class);
            if (detail != null) {
                TaskRouseDetail detail1 = this.selectById(detail.getId());
                String url = aliOSSComment.uploadByUrl(detail1.getOldUrl(),detail.getRouseId());
                detail1.setDownUrl(url);
                detail1.setModifyTime(LocalDateTime.now());
                detail1.setEnable(Whether.YES.getDbIndex());
                this.updateById(detail1);
            }
        }catch (Exception e){
            log.error("error",e);
        }

    }

    public TaskRouseDetail getSdk(String sdkKey) {
        TaskRouse rouse = rouseMapper.selectByKey(sdkKey);
        if (rouse == null) {
            return null;
        }
        LocalDateTime star=LocalDateTime.now().minusDays(30);
        List<Long> longs = taskRouseDetailMapper.selectIdList(rouse.getId(),star,LocalDateTime.now());
        if (longs.size() == 0) {
            return null;
        }

        int point = RandomUtils.nextInt(0, longs.size());
        return this.selectById(longs.get(point));
    }

    @Autowired
    private RedisCacheService redisCacheService;

    public List<ClickStrategyDetail> selectByStrategyId(Integer strategyId) {
        List<ClickStrategyDetail> appEatConfigs = redisCacheService.selectListByKey(KEY + strategyId, ClickStrategyDetail.class);
        if (appEatConfigs == null) {

            appEatConfigs = clickStrategyDetailMapper.selectByStrategyId(strategyId);
            if (appEatConfigs != null) {
                redisCacheService.addCacheListByKey(KEY + strategyId, JSON.toJSONString(appEatConfigs));
            }
        }
        return appEatConfigs;
    }

    public List<ClickStrategyDetail> filterList(List<ClickStrategyDetail> clickStrategyDetails, MemberClickRouse rouses, LocalDate now) {
        int k=0;
        int days =0;
        int t=0;
        for (ClickStrategyDetail s : clickStrategyDetails) {
            days= (int) now.until(rouses.getCreateTime().plusDays(s.getDayCount()).toLocalDate(), ChronoUnit.DAYS);
            if (rouses.getCreateTime().toLocalDate().plusDays(s.getDayCount()).equals(now)) {
                if (clidkRouseRecordMapper.checkClick(rouses.getMemberId(), rouses.getId(), now) > 0) {
                    //签过
                    s.setEnable(0);
                    t=2;
                } else {
                    //可签
                    s.setEnable(1);
                    t=1;
                }
            } else {
                if (rouses.getCreateTime().toLocalDate().plusDays(s.getDayCount()).isAfter(now)) {
                    //还未到
                    if (k == 0) {
                        //下一次签到
                        if(t==1){
                            s.setEnable(3);
                        }else if(t==2){
                            s.setEnable(2);
                        }else {
                            s.setEnable(2);
                        }
                        k = 1;
                    } else {
                        //下一次以后的全部签到
                        s.setEnable(3);
                    }
                    s.setClickDay(days);
                } else {
                    //已过
                    if (clidkRouseRecordMapper.checkClick(rouses.getMemberId(), rouses.getId(), rouses.getCreateTime().toLocalDate().plusDays(s.getDayCount()))>0) {
                        //签过
                        s.setEnable(0);
                    } else {
                        //漏签
                        s.setEnable(-1);
                    }
                }
            }
        }
        return clickStrategyDetails;
    }

    public void cleanAll(){
        List<String> appNameList=taskRouseDetailMapper.selectGroupByAppName();
        for(String appName:appNameList){
            TaskRouseDetailExample example=new TaskRouseDetailExample();
            example.createCriteria().andAppNameEqualTo(appName);
            List<TaskRouseDetail> list=selectByExample(example);
            Long firstId=list.get(0).getId();
            list.remove(0);
            aliOSSComment.deleteApkObject(list);
            example=new TaskRouseDetailExample();
            example.createCriteria().andAppNameEqualTo(appName).andIdNotEqualTo(firstId);
            taskRouseDetailMapper.deleteByExample(example);
        }
    }
}
